'''
Author: SUNNY
Description: 
Date: 2025-11-15 21:29:37
'''
"""
MCP 与 AI 集成示例
演示如何在 AI 对话中使用 MCP 工具
"""

from fastmcp import Client
import asyncio

class AIAssistant:
    """AI助手类，集成MCP工具"""

    def __init__(self, server_path):
        self.server_path = server_path

    async def process_query(self, user_query: str) -> str:
        """处理用户查询，智能调用MCP工具"""

        async with Client(self.server_path) as client:
            # 分析用户意图并调用相应工具
            if "加" in user_query or "+" in user_query:
                numbers = self._extract_numbers(user_query)
                if len(numbers) >= 2:
                    result = await client.call_tool("add", {"a": numbers[0], "b": numbers[1]})
                    return f"🔢 计算结果：{numbers[0]} + {numbers[1]} = {result.content[0].text}"
            elif "乘" in user_query or "*" in user_query or "×" in user_query:
                numbers = self._extract_numbers(user_query)
                if len(numbers) >= 2:
                    result = await client.call_tool("multiply", {"a": numbers[0], "b": numbers[1]})
                    return f"🔢 计算结果：{numbers[0]} × {numbers[1]} = {result.content[0].text}"
            elif "bmi" in user_query.lower() or "体重" in user_query:
                numbers = self._extract_numbers(user_query)
                if len(numbers) >= 2:
                    # 假设第一个是体重(kg)，第二个是身高(m)
                    result = await client.call_tool("calculate_bmi", {
                        "weight": numbers[0],
                        "height": numbers[1]
                    })
                    bmi_data = eval(result.content[0].text)
                    return (f"🏃‍♂️ BMI分析：\n"
                            f"• BMI指数: {bmi_data['bmi']}\n"
                            f"• 健康等级: {bmi_data['category']}\n"
                            f"• 专业建议: {bmi_data['advice']}")
            
            return "🤔 我主要擅长数学计算和BMI分析，请告诉我具体的计算需求吧！"

    def _extract_numbers(self, text: str) -> list:
        """从文本中提取数字"""
        import re

        numbers = re.findall(r"[-+]?\d*\.\d+|\d+", text)
        return [float(num) for num in numbers]
    
async def main():
    """主函数：演示AI助手的使用"""
    assistant = AIAssistant("simple_server.py")

    test_queries = [
        "请问25加38等于多少？",
        "计算一下6.5乘以4.2",
        "我的体重70公斤身高1.75米，帮我算下BMI",
        "今天天气怎么样？"
    ]

    print("🧠 AI助手演示开始...\n")

    for query in test_queries:
        print(f"👤 用户提问: {query}")
        response = await assistant.process_query(query)
        print(f"🤖 AI回答: {response}\n")

    print("🎉 演示结束！")

if __name__ == "__main__":
    asyncio.run(main())
